package com.project_doctor.service.impl;

import com.project_doctor.service.DashboardService;
import com.project_doctor.mapper.ResidentMapper;
import com.project_doctor.mapper.ContractMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private ResidentMapper residentMapper;

    @Autowired
    private ContractMapper contractMapper;

        @Override
    public Map<String, Object> getOverviewData() {
        Map<String, Object> result = new HashMap<>();

        Integer residentCount = residentMapper.getTotalResidentCount();
        Integer contractCount = contractMapper.getTotalContractCount();

        int serviceCount = contractCount != null ? contractCount * 60 : 600;

        int exceptionCount = 1;

        result.put("residentCount", residentCount != null ? residentCount : 0);
        result.put("contractCount", contractCount != null ? contractCount : 0);
        result.put("serviceCount", serviceCount);
        result.put("exceptionCount", exceptionCount);

        return result;
    }

    @Override
    public Map<String, Object> getTrendData() {
        Map<String, Object> result = new HashMap<>();

        List<String> dates = new ArrayList<>();
        List<Integer> residentData = new ArrayList<>();
        List<Integer> contractData = new ArrayList<>();
        List<Integer> serviceData = new ArrayList<>();

        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d");

        Integer totalResidents = residentMapper.getTotalResidentCount();
        Integer totalContracts = contractMapper.getTotalContractCount();

        int baseResidents = totalResidents != null ? totalResidents : 21;
        int baseContracts = totalContracts != null ? totalContracts : 10;

        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            dates.add(date.format(formatter));

            Map<String, Object> dayContract = contractMapper.getContractCountByDay(i);
            int dayContractCount = 0;
            if (dayContract != null && dayContract.get("count") != null) {
                dayContractCount = ((Number) dayContract.get("count")).intValue();
            }

            int residentCount = baseResidents - (int)(Math.random() * 5) + (int)(Math.random() * 5);
            residentData.add(residentCount);

            int contractCount = Math.max(0, baseContracts - i * 2 + dayContractCount);
            contractData.add(contractCount);

            int serviceCount = (int)(contractCount * 0.8) + (int)(Math.random() * 10);
            serviceData.add(serviceCount);
        }

        result.put("dates", dates);
        result.put("residentData", residentData);
        result.put("contractData", contractData);
        result.put("serviceData", serviceData);

        return result;
    }

    @Override
    public Map<String, Object> getTodoData() {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> todoList = new ArrayList<>();

        Map<String, Object> todo1 = new HashMap<>();
        todo1.put("number", 1);
        todo1.put("text", "待审核签约申请");
        todoList.add(todo1);

        Map<String, Object> todo2 = new HashMap<>();
        todo2.put("number", 30);
        todo2.put("text", "待审核服务申请");
        todoList.add(todo2);

        Map<String, Object> todo3 = new HashMap<>();
        todo3.put("number", 1);
        todo3.put("text", "待完成服务");
        todoList.add(todo3);

        Map<String, Object> todo4 = new HashMap<>();
        todo4.put("number", 107);
        todo4.put("text", "待回复消息");
        todoList.add(todo4);

        Map<String, Object> todo5 = new HashMap<>();
        todo5.put("number", 23);
        todo5.put("text", "待处理举报");
        todoList.add(todo5);

        result.put("todoList", todoList);
        return result;
    }

    @Override
    public Map<String, Object> getTagStats() {
        Map<String, Object> result = new HashMap<>();

        List<String> tagNames = Arrays.asList("高血压", "糖尿病", "冠心病", "肝硬化", "脑血栓", "心脏病");
        List<Integer> tagCounts = Arrays.asList(15, 8, 4, 3, 2, 3);

        result.put("tagNames", tagNames);
        result.put("tagCounts", tagCounts);

        return result;
    }

    @Override
    public Map<String, Object> getDoctorCards() {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> residents = residentMapper.selectResidentsWithHealthIssues();

        List<Map<String, Object>> doctorCards = new ArrayList<>();

        for (Map<String, Object> resident : residents) {
            Map<String, Object> card = new HashMap<>();
            card.put("id", resident.get("id"));
            card.put("name", resident.get("name"));
            card.put("title", "居民");
            card.put("status", resident.get("healthIssues"));
            card.put("avatar", resident.get("avatar") != null ?
                "http://localhost:8080/images/" + resident.get("avatar") :
                "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
            doctorCards.add(card);
        }

        result.put("doctors", doctorCards);
        return result;
    }

        @Override
    public Map<String, Object> getWeeklyData() {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> weeklyStats = contractMapper.selectWeeklyContractStats();

        LocalDate today = LocalDate.now();
        LocalDate monday = today.with(java.time.DayOfWeek.MONDAY);

        List<String> dateLabels = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            LocalDate date = monday.plusDays(i);
            dateLabels.add(date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }

        Map<String, Map<String, Integer>> teamDataMap = new HashMap<>();

        for (Map<String, Object> stat : weeklyStats) {
            String teamName = (String) stat.get("teamName");
            String signDate = stat.get("signDate").toString();
            Integer signCount = ((Number) stat.get("signCount")).intValue();

            if (teamName != null) {
                teamDataMap.computeIfAbsent(teamName, k -> new HashMap<>()).put(signDate, signCount);
            }
        }

        List<Map<String, Object>> weeklyData = new ArrayList<>();

        for (Map.Entry<String, Map<String, Integer>> entry : teamDataMap.entrySet()) {
            Map<String, Object> teamData = new HashMap<>();
            teamData.put("team", entry.getKey());

            Map<String, Integer> dailyData = entry.getValue();
            for (int i = 0; i < 7; i++) {
                String dateKey = "day" + (i + 1);
                String date = dateLabels.get(i);
                teamData.put(dateKey, dailyData.getOrDefault(date, 0));
            }
            weeklyData.add(teamData);
        }

        if (weeklyData.isEmpty()) {
            String[] defaultTeams = {"朝阳第一家庭医生团队", "海淀精英医疗团队", "西城健康守护团队"};
            for (String team : defaultTeams) {
                Map<String, Object> teamData = new HashMap<>();
                teamData.put("team", team);
                for (int i = 1; i <= 7; i++) {
                    teamData.put("day" + i, 0);
                }
                weeklyData.add(teamData);
            }
        }

        result.put("weeklyData", weeklyData);
        result.put("dateLabels", dateLabels);

        return result;
    }
}